package com.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.dao.HotEventsDao;
import com.pojo.HotEvents;
import com.util.R;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

@Service
public class HotEventsServiceImpl implements HotEventsService {

    @Autowired
    HotEventsDao hotEventsDao;

    @Override
    public R getHotEvents(Integer currentNo, String keyWord) {
        System.out.println("sqlsql---");
        R r = new R();
        try {
            PageHelper.startPage(currentNo, 3);
            List<HotEvents> projectInfoList = hotEventsDao.getHotEvents(keyWord);
            PageInfo<HotEvents> data = new PageInfo<>(projectInfoList);
            r.setData(data);
        } catch (Exception e) {
            r.setMessage("NO");
            r.setError(e.getMessage());
        }
        return r;
    }

    @Autowired
    @Qualifier("redisTemplate1")
    private RedisTemplate redisTemplate;

    @Override
    public R getHotEventInfo(Integer id) {
        R r = new R();
        try {
            HotEvents hotEventInfo = hotEventsDao.getHotEventInfo(id);
            Double score = redisTemplate.opsForZSet().score("HotEvents", hotEventInfo.getId() + "");
            if (score == null) {
                redisTemplate.opsForZSet().add("HotEvents", hotEventInfo.getId() + "", 1);
            } else {
                redisTemplate.opsForZSet().incrementScore("HotEvents", hotEventInfo.getId() + "", 1);
            }
            r.setData(hotEventInfo);
        } catch (Exception e) {
            r.setMessage("NO");
            r.setError(e.getMessage());
        }
        return r;
    }


    public void updateSearchSum() {
        Set<Object> range = redisTemplate.opsForZSet().range("HotEvents", 0, -1);
        Iterator<Object> iterator = range.iterator();
        while (iterator.hasNext()) {
            Object next = iterator.next();
            System.out.println(next);
            Double score = redisTemplate.opsForZSet().score("HotEvents", next);
            hotEventsDao.updateSearchSum(Integer.parseInt(next.toString()), Integer.parseInt(String.valueOf(score).trim().substring(0, String.valueOf(score).trim().indexOf("."))));
        }
        redisTemplate.opsForZSet().removeRange("HotEvents", 0, -1);
    }
}
